package com.jxj.study.controller.executors;

import com.jxj.study.allConfig.beans.DelayQueueManagers;
import com.jxj.study.domian.DelayTask;
import com.jxj.study.util.RunnableTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;

@RestController
@RequestMapping("/executor")
public class ExecutorController {

    @Qualifier("taskExecutor")
    @Autowired
    private Executor exception;

    //提交任务
    //
    //    无返回值的任务使用execute(Runnable)
    //
    //    有返回值的任务使用submit(Runnable)
    @Autowired
    private ExecutorService executorService;

    @Autowired
    private DelayQueueManagers<DelayTask> delayQueueManagers;

    @RequestMapping
    public void exceptionTest(Integer integer){
        for (int i = 0; i < integer; i++) {
            ArrayList<String> strings = new ArrayList<>();
            strings.add("strings"+(i+1));
            RunnableTask runnableTask = new RunnableTask(strings);
            runnableTask.setName(UUID.randomUUID().toString());
            exception.execute(runnableTask);
        }
    }

    @RequestMapping("delayTask")
    public void delay(){
        DelayQueue<DelayTask> queue = delayQueueManagers.getQueue();
        if (queue.size()>0){
            System.out.println("queue.size:"+queue.size());
            DelayTask take = delayQueueManagers.take();
            take.setExpireTime(take.getExpireTime() + 1000);
            executorService.execute(() -> System.out.println(take.getExpireTime()));
        }
    }

    @RequestMapping("/addTask")
    public void addTask(){
        for (int i = 0; i < 10; i++) {
            DelayTask delayTask = new DelayTask((i+1) * 1000);
            delayQueueManagers.put(delayTask);
        }
        delay();
    }
}
